const jwt =require('jsonwebtoken');
const{User}=require('../models');

module.exports = async (req,res, next) =>{
    try{
        //判断Token是否存在
        const { token }=req.headers;
        if(!token){
            res.status(500).json({
                status: false, 
                message: 'error',
                error: ['未登录']
            })
        } else {
             //验证 token是否正确
            const decoded = jwt.verify(token, process.env.SECRET);
            //从jwt中,解析出之前存入的userId
            const{userId}=decoded;
            console.log( decoded)
            const user = await User.findByPk(userId)
            if(!user) {
                res.status(500).json({
                    status: false, 
                    message: 'error',
                    error: ['登录用户不存在']
                })

            }else {
                req.user = user
                req.user_id = user.user_id
                next()
            }
        }
       
    }catch(error){
        res.status(500).json({
            status: false, 
            message: 'error',
            error: [error.message]
        })
    }

};